package cs9322.assign3.resources;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import cs9322.assign3.dao.OrdersDao;
import cs9322.assign3.dao.PaymentDao;
import cs9322.assign3.dao.PaymentsDao;
import cs9322.assign3.model.Order;
import cs9322.assign3.model.Payment;

@Path("/payments")
public class PaymentsResource {

		@Context
		UriInfo uriInfo;
		@Context
		Request request;
		

		
		@GET
		@Produces(MediaType.TEXT_XML)
		public List<Payment> getPaymentBrowser() {
			List<Payment> pl = new ArrayList<Payment>();
//			pl.addAll(PaymentsDao.instance.getStore().values());
			PaymentDao pd = new PaymentDao();
			pl = pd.getAllPayments();
			return pl;
		}
		
		@PUT
		@Produces(MediaType.TEXT_XML)
		@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
		public Payment newPayment(
				@FormParam("oid") int id,
				@FormParam("type") String type,
				@FormParam("amount") double amount,
				@FormParam("detail") String detail){
			
			PaymentDao pd = new PaymentDao();
//			Payment test = pd.findByOrderId(id);
			if(pd.findByOrderId(id) == null){
//				pd.add(p);
				Payment p = new Payment(id,type,amount,detail);
				URI uri = uriInfo.getAbsolutePathBuilder().path(Integer.toString(id)).build();
				p.setUrl(uri.toString());
				Response.created(uri).build();
				pd.add(p);
//				pd.update(p);
				return p;
			}else{
				Payment p = pd.findByOrderId(id);
				p.setPaymentType(type);
				p.setPaymentAmount(amount);
				p.setPaymentDetail(detail);
				pd.update(p);
				return p;
			}
			
		
		}
		
//		@POST
//		@Produces(MediaType.TEXT_XML)
//		@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
//		public Order newOrder(
//				@FormParam("id") int id,
//				@FormParam("type") String type,
//				@FormParam("size") String size,
//				@FormParam("paid") boolean paid,
//				@FormParam("addition") String addition,
//				@Context HttpServletResponse servletResponse
//		) throws IOException {
//			Order o = new Order(id, type, size, paid, addition);
//			OrdersDao.instance.getStore().put(Integer.toString(id), o);
//			URI uri = uriInfo.getAbsolutePathBuilder().path(Integer.toString(id)).build();
//			o.setUrl(uri.toString());
//			Response.created(uri).build();
//			return o;
//		}
		
		
		@Path("{payment}")
		public PaymentResource getPayment(
				@PathParam("payment")  int id) {
			return new PaymentResource(uriInfo, request, id);
		}
	}
